 
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

import { login , getInfo} from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'

// 设置全局访问的state对象
const state = {
    count : 99,
    routerList:[],
    token: getToken(),
    username: '',
    avatar: '',
    roleMenList: [] // 权限路由
}

const getters = { //实时监听state值变化
    isChangeNum (state) {
        return state.count
    }

}

const mutations= {
    addCount(state,num){
        state.count = Number(state.count )+ Number(num)
    },
    delCount(state,num){
        state.count = Number(state.count) - Number(num)
    },
    changeRouterList(state,value) {
        state.routerList = value
    },
    addMenuList(state,value){
      
      state.roleMenList = value
    },
    SET_TOKEN: (state, token) => {
        state.token = token
      },
      SET_NAME: (state, name) => {
        state.username = name
      },
      SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
      }

}

const actions = {
    login({ commit }, userInfo) {
        const { password, phone } = userInfo
        return new Promise((resolve, reject) => {
          login({ phone: phone, password: password }).then(response => {
            const { data } = response
            commit('SET_TOKEN', data)
            setToken(data)
            
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      },



        // user logout
  logout({ commit, state, dispatch }) {
        commit('SET_TOKEN', '')
        removeToken()
    // return new Promise((resolve, reject) => {
    //     debugger
    //   logout(state.token).then(() => {
    //     commit('SET_TOKEN', '')
    //     commit('SET_ROLES', [])
    //     removeToken()
    //     // resetRouter()
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },
}
const store = new Vuex.Store({
    state,
    getters,
    mutations,
    actions
});
 
export default store;